<template>
    <div class="calendar-container">
        <header>
            <i class="fa fa-angle-left" onclick="history.go(-1)"></i>
            <p>我的预约</p>
            <div></div>
        </header>
        <h1 style="align-items: center; text-align: center ; margin-top: 20px;">{{ currentMonthYear }}</h1>
        <div class="calendar-header">
            <button @click="changeMonth(-1)" class="nav-button">&lt;</button>
            <h2>{{ currentMonthYear }}</h2>
            <button @click="changeMonth(1)" class="nav-button">&gt;</button>
        </div>
        <div class="calendar-grid">
            <div v-for="day in ['日', '一', '二', '三', '四', '五', '六']" :key="day" class="calendar-cell header">
                {{ day }}
            </div>
            <div
                v-for="(date, index) in calendarDays"
                :key="index"
                class="calendar-cell"
                :class="{
                    'current-month': date.currentMonth,
                    'other-month': !date.currentMonth,
                    available: isAvailableForBooking(date.date),
                    selected: isDateSelected(date.date),
                }"
            >
                <button @click="selectDate(date)" :disabled="!isAvailableForBooking(date.date)" class="date-button">
                    <span>{{ formatDay(date.date) }}</span>
                    <span v-if="isAvailableForBooking(date.date)" class="available-slots">
                        {{ getAvailableSlots(date.date) }}
                    </span>
                </button>
            </div>
        </div>
        <div v-if="selectedDate" class="selected-date-info">
            <p>选择的日期: {{ formatDate(selectedDate) }}</p>
            <p>可用预约数: {{ getAvailableSlots(selectedDate) }}</p>
            <button @click="toConfirmOrder">确认</button>
        </div>
    </div>
</template>

<script setup>
import "../style/css/selectdate.css"
import {ref, computed, reactive} from "vue";
import {useRouter, useRoute} from "vue-router";
import {onMounted} from "vue";
import axios from "axios";

const router = useRouter();
const route = useRoute();
const currentDate = ref(new Date());
const selectedDate = ref(null);
const appointmentSlots = reactive({});
const available = ref([]);
onMounted(async () => {
    console.log(currentDate.value.getMonth());
    axios
    .post("/api/calender/getCalendarInfo", {
        hpId: route.query.hospitalId,
        year: currentDate.value.getFullYear(),
        month: currentDate.value.getMonth() + 1,
    })
    .then((res) => {
        const data = res.data.data;
        data.forEach((item, index) => {
            appointmentSlots[item.ymd] = {
                existing: item.existing,
                remainder: item.remainder,
                total: item.total,
                ymd: item.ymd,
            };
        });
    })
    .catch((err) => {
        console.log(err);
    });
});
// 安全地获取年份
const safeGetFullYear = (date) => {
    if (date instanceof Date && !isNaN(date)) {
        return date.getFullYear();
    }
    console.error("无效的日期对象");
    return null;
};

// 安全地获取月份
const safeGetMonth = (date) => {
    if (date instanceof Date && !isNaN(date)) {
        return date.getMonth();
    }
    console.error("无效的日期对象");
    return null;
};

// 生成日历数据
const calendarDays = computed(() => {
    const year = safeGetFullYear(currentDate.value);
    const month = safeGetMonth(currentDate.value);
    if (year === null || month === null) return [];

    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);

    const days = [];
    const daysFromPrevMonth = firstDay.getDay();
    const daysFromNextMonth = 6 - lastDay.getDay();

    // 上个月的日期
    for (let i = daysFromPrevMonth; i > 0; i--) {
        const date = new Date(year, month, -i + 1);
        days.push({date, currentMonth: false});
    }

    // 当前月的日期
    for (let i = 1; i <= lastDay.getDate(); i++) {
        const date = new Date(year, month, i);
        days.push({date, currentMonth: true});
    }

    // 下个月的日期
    for (let i = 1; i <= daysFromNextMonth; i++) {
        const date = new Date(year, month + 1, i);
        days.push({date, currentMonth: false});
    }

    return days;
});

// 当前月份和年份
const currentMonthYear = computed(() => {
    const year = safeGetFullYear(currentDate.value);
    const month = safeGetMonth(currentDate.value);
    if (year === null || month === null) return "无效日期";

    const options = {year: "numeric", month: "long"};
    return new Intl.DateTimeFormat("zh-CN", options).format(currentDate.value);
});

// 检查日期是否可以预约（未来30天）
const isAvailableForBooking = (date) => {
    if (!(date instanceof Date) || isNaN(date)) return false;

    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const futureLimit = new Date(today);
    futureLimit.setDate(today.getDate() + 30);
    return date >= today && date < futureLimit;
};

// 获取或生成可用预约数
const getAvailableSlots = (date) => {
    if (!isAvailableForBooking(date)) return 0;
    console.log(date);
    const dateString = formatDate(date);
    return appointmentSlots[dateString]?.remainder || 0;
};

// 格式化日期 (YYYY-MM-DD)
const formatDate = (date) => {
    if (!(date instanceof Date) || isNaN(date)) return "无效日期";
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
};

// 格式化日 (DD)
const formatDay = (date) => {
    if (!(date instanceof Date) || isNaN(date)) return "无效";
    return String(date.getDate()).padStart(2, "0");
};

// 选择日期
const selectDate = (dateObj) => {
    if (isAvailableForBooking(dateObj.date)) {
        selectedDate.value = dateObj.date;
    }
};
const toConfirmOrder = () => {
    console.log(formatDate(selectedDate));
    router.push({
        path: "/confirmorder",
        query: {
            hospitalId: route.query.hospitalId,
            setmealId: route.query.setmealId,
            date: formatDate(selectedDate.value),
        },
    });
};
// 检查日期是否被选中
const isDateSelected = (date) => {
    return selectedDate.value && formatDate(date) === formatDate(selectedDate.value);
};

// 改变月份
const changeMonth = (delta) => {
    const newDate = new Date(currentDate.value);
    newDate.setMonth(newDate.getMonth() + delta);
    currentDate.value = newDate;
};
</script>

<style scoped>
.calendar-container {
    max-width: 400px;
    margin: 0 auto;
    font-family: Arial, sans-serif;
}

.calendar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

header{
    width: 100%;
    height: 15.7vw;
    background-color: #FFF;

    position: fixed;
    left: 0;
    top: 0;

    display: flex;
    align-items: center;
    justify-content: space-between;

    box-sizing: border-box;
    padding: 0 3.6vw;
}
header .fa{
    font-size: 8vw;
}


.nav-button {
    background: none;
    border: none;
    font-size: 18px;
    cursor: pointer;
}

.calendar-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 5px;
}

.calendar-cell {
    aspect-ratio: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 14px;
}

.calendar-cell.header {
    font-weight: bold;
}

.date-button {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: none;
    border: none;
    cursor: pointer;
}

.current-month .date-button {
    background-color: #f0f0f0;
}

.other-month .date-button {
    color: #999;
}

.available .date-button {
    background-color: #e6f7ff;
}

.selected .date-button {
    background-color: #1890ff;
    color: white;
}

.available-slots {
    font-size: 10px;
    margin-top: 2px;
}

.selected-date-info {
    margin-top: 20px;
    text-align: center;
}
</style>
